import 'dart:io';
import 'dart:math';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:share_fit/app/components/back_btn_icon.dart';
import 'package:share_fit/app/controllers/device/alarm/alarm_add_warn.dart';
import 'package:share_fit/app/controllers/device/alarm/alarm_del_dialog.dart';
import 'package:share_fit/app/controllers/device/alarm/alarm_item.dart';
import 'package:share_fit/app/helper/ext/tr_ext.dart';
import 'package:share_fit/app/tools/color_const.dart';
import 'package:share_fit/generated/locales.g.dart';
import 'package:sprintf/sprintf.dart';

import 'alarm_logic.dart';

class AlarmPage extends StatelessWidget {
  AlarmPage({Key? key}) : super(key: key);

  final logic = Get.put(AlarmLogic());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(LocaleKeys.ai_alarm.ts, style: TextStyle(fontSize: 54.sp, color: ColorConst.btnFontColor),),
        centerTitle: true,
        leading: BackBtnIcon(onTap: () => Get.back()),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            Container(height: 99.h,),
            Image(
              width: 454.w,
              height: 317.h,
              image: const AssetImage("assets/images/device/icon_alarm_top.png"),),
            Container(
              margin: EdgeInsets.fromLTRB(42.w, 116.h, 42.w, 0),
              child: Text(LocaleKeys.alarm_tips.ts, style: TextStyle(fontSize: 42.sp, color: Color(0xFF2B2B2B)),),
            ),
            Container(
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(10),
                  color: Colors.white
              ),
              margin: EdgeInsets.fromLTRB(42.w, 100.h, 42.w, 0),
              child: GetBuilder<AlarmLogic>(
                id: 'update_alarm_datas',
                builder: (_) { //logic.state.itemDatas
                  return Visibility(
                      visible: !logic.state.isLoading,
                      replacement: CircularProgressIndicator(color: ColorConst.accentColor,),
                      child: Visibility(
                        visible: logic.state.itemDatas.isNotEmpty,
                        child: ListView.separated(
                            shrinkWrap: true,
                            physics: const NeverScrollableScrollPhysics(),
                            itemBuilder: (BuildContext context, int index) {
                              return _buildListTitle(context, index);
                            },
                            separatorBuilder: (BuildContext context, int index) {
                              return Container(height: 1, color: Color(0xFFD7D7D7),);
                            },
                            itemCount: min(5, logic.state.itemDatas.length)),
                      )
                  );

                  },),
            ),
            Column(
              children: [
                logic.state.itemDatas.isNotEmpty ? Container(
                  padding: EdgeInsets.all(10.w),
                  margin: EdgeInsets.fromLTRB(42.h, 84.h, 42.h, 0.h),
                  child: Text(LocaleKeys.alarm_long_press_tips.ts, style: TextStyle(
                      fontSize: 40.sp,
                      color: Colors.grey
                  ),),
                ) : Container(),
                Row(
                  children: [
                    Expanded(
                        child: Container(
                          height: 136.h,
                          margin: EdgeInsets.fromLTRB(42.h, 54.h, 42.h, 154.h),
                          child: ElevatedButton(
                            onPressed: () {
                              if(logic.state.itemDatas.length>=5) {
                                showDialog(context: context, builder: (_) {
                                  return AddWarnDialog();
                                });
                                return;
                              }
                              Get.toNamed('/device/alarm/add', arguments: {"isEdit": false});
                              },
                            style: ButtonStyle(
                                backgroundColor: MaterialStateProperty.all(ColorConst.activeColor),
                                shape: MaterialStateProperty.all(RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(10)
                                ))
                            ),
                            child: Text(LocaleKeys.alarm_edit.ts, style: TextStyle(fontSize: 48.sp, color: Colors.white, ),),
                          ),
                        )),
                  ],)
              ],
            ),
          ],
        ),),);
  }

  Widget _buildListTitle(BuildContext context, int index) {
    return GestureDetector(
        behavior: HitTestBehavior.opaque,
        onLongPress: ()=>{
          showDialog(context: context, builder: (_){
            return AlarmDelDialog(callback: (){
              logic.state.itemDatas.removeAt(index);
              logic.setAlarmList(back: (result){
                logic.updateItem();
                logic.showInfoDialog(LocaleKeys.sos_number_del_success.ts);
              });
            });
          })
        },
        onTap: ()=> {
          Get.toNamed('/device/alarm/add', arguments: {"isEdit": true, "index": index})
        },
        child: Container(
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(10),
              color: Colors.white
          ),
          padding: EdgeInsets.fromLTRB(60.w, 20.h, 36.w, 64.h),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(getAlarmAmPm(logic.state.itemDatas[index]), style: TextStyle(fontSize: 42.sp, color: ColorConst.primaryFontColor),),
                    GetBuilder<AlarmLogic>(
                        id: 'alarm_enable',
                        builder: (_){
                          return Transform.scale(
                              scale: 0.7,
                              child: CupertinoSwitch(
                                  value: logic.state.itemDatas[index].enable,
                                  activeColor: ColorConst.accentColor,
                                  onChanged: (value) {
                                    logic.state.itemDatas[index].enable = value;
                                    logic.showLoading();
                                    logic.setAlarmList(back: (result){
                                      logic.cancelLoading();
                                      if (!result) {
                                        logic.state.itemDatas[index].enable = !value;
                                      }
                                      logic.update(['alarm_enable']);
                                      print(result);
                                    });
                                  }));
                    })
                  ]),
              Text(getAlarmTime(logic.state.itemDatas[index]), style: TextStyle(fontSize: 36.sp, color: Color(0xFF898C8F)))
            ],),)
    );
  }

  getAlarmAmPm(AlarmItem item) {
    int hour = item.hour;
    String h = hour.toString().padLeft(2, '0');
    String minute = item.minute.toString().padLeft(2, '0');
    String timeAmPm="";
    if(hour<12) {
      timeAmPm = '${sprintf(LocaleKeys.settings_start_time_morning.ts, [''])} $h:$minute';
    } else {
      timeAmPm = '${sprintf(LocaleKeys.settings_end_time_afternoon.ts, [''])} $h:$minute';
    }
    return timeAmPm;
  }

  getAlarmTime(AlarmItem item) {
    String result = '';
    // int radix = int.parse(item.cycleList[0].toRadixString(2));
    int radix = item.cycleList[0];

    if(radix==logic.state.WeekCycleONCE) {
      return LocaleKeys.alarm_never.ts;
    }

    // if(radix&logic.state.WeekCycleEVERYDAY==logic.state.WeekCycleEVERYDAY) {
    //   print('22222');
    //   return LocaleKeys.alarm_everyday.ts;
    // } else if(radix&logic.state.WeekCycleWORKDAY==logic.state.WeekCycleWORKDAY) {
    //   print('33333');
    //   return LocaleKeys.alarm_workday.ts;
    // }

    int isWorkDay = 0;
    if(Platform.isIOS) {
      if(radix&logic.state.WeekCycleMONDAYIOS==logic.state.WeekCycleMONDAYIOS) {
        result += LocaleKeys.alarm_week_monday.ts;
        result += ' ';
        isWorkDay++;
      }

      if(radix&logic.state.WeekCycleTUESDAYIOS==logic.state.WeekCycleTUESDAYIOS) {
        result += LocaleKeys.alarm_week_tuesday.ts;
        result += ' ';
        isWorkDay++;
      }

      if(radix&logic.state.WeekCycleWEDNESDAYIOS==logic.state.WeekCycleWEDNESDAYIOS) {
        result += LocaleKeys.alarm_week_wednesday.ts;
        result += ' ';
        isWorkDay++;
      }

      if(radix&logic.state.WeekCycleTHURSDAYIOS==logic.state.WeekCycleTHURSDAYIOS) {
        result += LocaleKeys.alarm_week_thursday.ts;
        result += ' ';
        isWorkDay++;
      }

      if(radix&logic.state.WeekCycleFRIDAYIOS==logic.state.WeekCycleFRIDAYIOS) {
        result += LocaleKeys.alarm_week_friday.ts;
        result += ' ';
        isWorkDay++;
      }

      if(radix&logic.state.WeekCycleSATURDAYIOS==logic.state.WeekCycleSATURDAYIOS) {
        result += LocaleKeys.alarm_week_saturday.ts;
        result += ' ';
        isWorkDay--;
      }

      if(radix&logic.state.WeekCycleSUNDAYIOS==logic.state.WeekCycleSUNDAYIOS) {
        result += LocaleKeys.alarm_week_sunday.ts;
        isWorkDay--;
      }
    } else {
      if(radix&logic.state.WeekCycleMONDAY==logic.state.WeekCycleMONDAY) {
        result += LocaleKeys.alarm_week_monday.ts;
        result += ' ';
        isWorkDay++;
      }

      if(radix&logic.state.WeekCycleTUESDAY==logic.state.WeekCycleTUESDAY) {
        result += LocaleKeys.alarm_week_tuesday.ts;
        result += ' ';
        isWorkDay++;
      }

      if(radix&logic.state.WeekCycleWEDNESDAY==logic.state.WeekCycleWEDNESDAY) {
        result += LocaleKeys.alarm_week_wednesday.ts;
        result += ' ';
        isWorkDay++;
      }

      if(radix&logic.state.WeekCycleTHURSDAY==logic.state.WeekCycleTHURSDAY) {
        result += LocaleKeys.alarm_week_thursday.ts;
        result += ' ';
        isWorkDay++;
      }

      if(radix&logic.state.WeekCycleFRIDAY==logic.state.WeekCycleFRIDAY) {
        result += LocaleKeys.alarm_week_friday.ts;
        result += ' ';
        isWorkDay++;
      }

      if(radix&logic.state.WeekCycleSATURDAY==logic.state.WeekCycleSATURDAY) {
        result += LocaleKeys.alarm_week_saturday.ts;
        result += ' ';
        isWorkDay--;
      }

      if(radix&logic.state.WeekCycleSUNDAY==logic.state.WeekCycleSUNDAY) {
        result += LocaleKeys.alarm_week_sunday.ts;
        isWorkDay--;
      }
    }

    if(isWorkDay==5) {
      result = LocaleKeys.alarm_workday.ts;
    }

    if(isWorkDay==7) {
      result = LocaleKeys.alarm_everyday.ts;
    }

    return result;
  }
}
